﻿/*----------------------------------------------------------------
 * 
 * 版权所有：Copyright (C) 2013
 * 
 * 文件名：Extensions.cs
 * 文件功能描述：
 * 
 * 
 * 作 者：zhangq
 * 邮 箱：ifunnyface@outlook.com
 * 日 期：2013-01-07 16:02:43
 * 
 * 
 * 修改标识： Author
 * 修改描述： 相关描述
 * 
 * ---------------------------------------------------------------- */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace EntityFrameworkExtension
{

    /// <summary>
    /// 
    /// </summary>
    public static class OrderExtension
    {

       
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="propertyName"></param>
        /// <param name="ascending"></param>
        /// <returns></returns>
        public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName, bool ascending) 
            where T : class
        {
            Type type = typeof(T);

            PropertyInfo property = type.GetProperty(propertyName);
            if (property == null)
                throw new ArgumentException("propertyName", "Not Exist");

            ParameterExpression param = Expression.Parameter(type, "p");
            Expression propertyAccessExpression = Expression.MakeMemberAccess(param, property);
            LambdaExpression orderByExpression = Expression.Lambda(propertyAccessExpression, param);

            string methodName = ascending ? "OrderBy" : "OrderByDescending";

            MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExpression));

            return source.Provider.CreateQuery<T>(resultExp);
        }
         
    }

}